import React, {Component} from 'react';
import ReactDOM from 'react-dom';



class Menu extends Component {

  constructor(props) {
    super(props);

    this.nodeW=0;
    this.nodeH=0;
    this.docl=document.documentElement.clientWidth;
    this.docH=document.documentElement.clientHeight;

    this.state={
      isOpen:true,
      left:0,
      top:0
    }

    this.show=this.show.bind(this);

    document.addEventListener('scroll',()=>{this.hide()});
    document.addEventListener('click',()=>{this.hide()});
  }

  show(left,top){
    this.setState({isOpen:true,left:left,top:top});
  }

  hide(){
    this.setState({isOpen:false});
  }

  clickItem(cb,event){
    event.stopPropagation();
    event.preventDefault();
    if(Object.prototype.toString.call(cb) == "[object Function]"){
      cb();
    }
  }

  //在这里取到menu的宽和高
  componentDidMount() {
    const node=ReactDOM.findDOMNode(this);

    this.nodeW=node.clientWidth;
    this.nodeH=node.clientHeight;
    this.hide();
  }

  render() {

      let cl=this.state.left;
      let ct=this.state.top;

      //判断是否靠近边界
      if((this.state.left+this.nodeW)>this.docl){
          cl=this.state.left-this.nodeW;
      }

      if((this.state.top+this.nodeH)>this.docH){
          ct=this.state.top-this.nodeH;
      }


    const style={
      left:cl,
      top:ct,
      display:this.state.isOpen?'block':'none'
    }


    const menuList=this.props.menuList.map((item,index)=>{
        return (<li key={index} onContextMenu={this.clickItem.bind(this,item.callback)} onClick={this.clickItem.bind(this,item.callback)}>{item.title}</li>)
    });

    return (
      <ul className="context-menu" style={style}>
          {menuList}
      </ul>
    );
  }
}



class ContextMenu extends Component {
    constructor(props){
        super(props);

        this.state={
          left:0,
          top:0
        }
    }

    render() {

        return(
            <div onContextMenu={this.layout.bind(this)} style={{display:this.props.display||'block'}}>
                {this.props.children}
                <Menu menuList={this.props.menuList} ref="menu"/>
            </div>
        );
    }

    layout(event){
        event.stopPropagation();
        event.preventDefault();

        this.refs.menu.show(event.clientX,event.clientY);
    }
}

export default ContextMenu;
